package com.hr.reactive.operators;

import com.hr.reactive.common.Utils;
import com.hr.reactive.mono.s02.Lec04MonoEmptyTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class Lec05ErrorHandle {
    private static final Logger log = LoggerFactory.getLogger(Lec05ErrorHandle.class);

    public static void main(String[] args) {
        onErrorContinue();
    }

    private static void onErrorContinue(){
        Flux.range(1,10)
                .map(i->i==5?5/0:i)
                .onErrorContinue((ex,obj)->log.warn("{}",obj,ex))
                .subscribe(Utils.subscriber());
    }
    private static void onErrorComplete(){
        Flux.range(1,10)
                .map(i->i==5?5/0:i)
                .onErrorComplete()
                .subscribe(Utils.subscriber());
    }
    private static void onErrorReturn(){
        Flux.range(1,10)

                .map(i->i==5?5/0:i)
                //发生异常的时候返回一个默认值
                //.onErrorReturn(-1)
                .onErrorReturn(IllegalArgumentException.class,-1)
                .onErrorReturn(ArithmeticException.class,-1)

                .subscribe(Utils.subscriber());
    }
    private static void onErrorResume(){
        Mono.just(5)

                .map(i->i==5?5/0:i)
                //有错误调用备份方法返回值
                .onErrorResume(ex->fallback())
                .onErrorResume(ArithmeticException.class,ex->fallback())
                .onErrorReturn(-4)
                .subscribe(Utils.subscriber());
    }
    private static Mono<Integer> fallback(){
       return Mono.fromSupplier(()->Utils.faker().random().nextInt(10,100));
    }
}
